# coding:utf-8
import os
import sys
import traceback

from loguru import logger
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QApplication
from qfluentwidgets import FluentTranslator

from common import cfg, LOG_DIR, signalBus
from view import MainWindow


def exception_hook(exception: BaseException, value, tb):
    """ 异常回调函数 """
    message = '\n'.join([''.join(traceback.format_tb(tb)),
                         '{0}: {1}'.format(exception.__name__, value)])
    logger.error(message)
    signalBus.appErrorSig.emit(message)


# enable dpi scale
if cfg.get(cfg.dpiScale) != "Auto":
    os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "0"
    os.environ["QT_SCALE_FACTOR"] = str(cfg.get(cfg.dpiScale))

# create application
app = QApplication(sys.argv)
app.setAttribute(Qt.ApplicationAttribute.AA_DontCreateNativeWidgetSiblings)
# 错误处理
sys.excepthook = exception_hook

# internationalization
locale = cfg.get(cfg.language).value
translator = FluentTranslator(locale)
app.installTranslator(translator)
logger.add(LOG_DIR / 'application.log', rotation="10 MB", encoding='utf-8', enqueue=True)
# create main window
w = MainWindow()
w.show()

app.exec()
